package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("add")
    public String addTest(String userName,String passWord) throws  Exception
    {
        String sql="insert into user (USERNAME,PASSWORD) VALUE (?,?)";
        int row=jdbcTemplate.update(sql,userName,passWord);
        return "执行成功，影响"+row+"行";
    }

    @GetMapping("updateUserPassword")
    public String updateUserPassword(int id,String passWord) throws  Exception
    {
        String sql="UPDATE user set PASSWORD =? WHERE ID=?";
        int row=jdbcTemplate.update(sql,passWord,id);
        return "执行成功，影响"+row+"行";
    }

    @GetMapping("deleteUserById")
    public String deleteUserById(int id) throws  Exception
    {
        String sql="delete from user where ID=?";
        int row=jdbcTemplate.update(sql,id);
        return "执行成功，影响"+row+"行";
    }

    @GetMapping("saveUserTest")
    public String saveUserTest() throws  Exception
    {
        String sql="insert into user (username,password) VALUE ('yxh',123456)";
        int row=jdbcTemplate.update(sql);
        return "执行成功，影响"+row+"行";
    }

    @GetMapping("getUserByName")
    public List getUserByName(String username) throws  Exception
    {
        String sql="select * from user where ID=?";
        List<User> list=jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class),username);
        return list;
    }

    @GetMapping("getMapById")
    public Map getMapById(Integer id) throws  Exception
    {
        String sql="select * from user where ID=?";
        Map map=jdbcTemplate.queryForMap(sql,id);
        return map;
    }

    @GetMapping("getUserById")
    public User getUserById(Integer id) throws  Exception
    {
        String sql="select  * from user where id=?";
        int row=jdbcTemplate.update(sql);
        User user=jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),id);
        return user;
    }

    @GetMapping("batchSave")
    public String batchSave() throws Exception
    {
        String sql="insert into user (USERNAME,PASSWORF) VALUE (?,?)";
        List<Object[]> arraylist=new ArrayList<>();
        for (int i=0;i<10;i++)
        {
            String [] arr=new String[2];
            arr[0]="yxh"+i;
            arr[1]="123456"+i;
            arraylist.add(arr);
        }
        jdbcTemplate.batchUpdate(sql,arraylist);
        return "执行成功";
    }

}
